import React, { Component } from 'react';
import { View, Text, Button, Image } from 'react-native';
import { FlatList, TouchableOpacity } from 'react-native-gesture-handler';

export default class List extends Component {
  constructor(props) {
    super(props);
    this.url = 'http://www.cjlly.com:3045/record';
    this.max = 7;
    this.state = { data: [], albums: [] };
  }

  _ItemSeparatorComponent = () => {
    return <View style={{ height: 2, backgroundColor: 'blue' }} />;
  };

  componentDidMount () {
    fetch(this.url, { method: 'GET' })
      .then(resp => resp.json())
      .then(albums => {
        this.setState({ albums: albums });
      });
  }

  _del = id => {
    let data = this.state.albums.splice(0);
    let index = data.findIndex(albums => albums.id === id);
    console.log(index, id);
    data.splice(index, 1);
    this.setState({ albums: data });
  };

  _goItem = item => {
    let params = { item: item };
    this.props.navigation.navigate('详情', params);
  };

  _RenderItem = ({ item }) => {
    return (
      <View style={{ flexDirection: 'row' }}>
        <TouchableOpacity
          onPress={() => this._goItem(item)}
          style={{ width: 350, flexDirection: 'row' }}>
          <Text style={{ flexBasis: 30 }}>{item.id}</Text>

          <Image style={{ width: 80, height: 80 }} source={{ uri: item.img }} />

          <Text style={{ width: 80, marginLeft: 20 }}>{item.name}</Text>
        </TouchableOpacity>

        <Button
          style={{ width: 100, height: 30 }}
          onPress={() => this._del(item.id)}
          title="删除"
        />
      </View>
    );
  };

  _refresh = () => {
    let d = Math.floor(Math.random() * 100 + 100);
    let data = this.state.data.splice(0);
    data.unshift(d);
    this.setState({ data: data });
  };

  _reachEnd = () => {
    let data = this.state.data.splice(0);
    data.push(++this.max);
    this.setState({ data: data });
  };

  render () {
    return (
      <View>
        <FlatList
          ListEmptyComponent={<Text>没有数据</Text>}
          keyExtractor={({ item, index }) => index}
          ItemSeparatorComponent={this._ItemSeparatorComponent}
          data={this.state.albums}
          renderItem={this._RenderItem}
          refreshing={false}
          onRefresh={this._refresh}
          onEndReached={this._reachEnd}
          onEndReachedThreshold={0.2}
        />
      </View>
    );
  }
}
